<template>
  <div class="level-detail">
    <div class="page-header">
      <div class="header-top">
        <button class="back-btn" @click="goBackToList">← 返回关卡列表</button>
        <h1>{{ levelDetail.level_name || '关卡详情' }}</h1>
        <div class="spacer"></div>
      </div>
    </div>
    
    <div class="level-content">
      <div class="level-info-card">
        <h2>关卡信息</h2>
        <p><strong>关卡名称:</strong> {{ levelDetail.level_name }}</p>
        <p><strong>题目数量:</strong> {{ levelDetail.total_questions }}</p>
        <p><strong>已完成:</strong> {{ levelDetail.answered_questions }}/{{ levelDetail.total_questions }}</p>
        <p><strong>正确率:</strong> {{ levelDetail.accuracy_rate ? (levelDetail.accuracy_rate * 100).toFixed(1) + '%' : '暂无' }}</p>
        <p><strong>奖励积分:</strong> {{ levelDetail.points || 0 }} 碳积分</p>
        <p><strong>星级:</strong> <template v-if="levelDetail.stars || calculateStars(levelDetail) > 0">
          <span class="star filled" v-for="n in (levelDetail.stars || calculateStars(levelDetail))" :key="'filled-' + n">★</span>
          <span class="star empty" v-for="n in (3 - (levelDetail.stars || calculateStars(levelDetail)))" :key="'empty-' + n">☆</span>
        </template><template v-else>暂无</template></p>
        <p><strong>时间限制:</strong> {{ levelDetail.time_limit || 10 }} 分钟</p>
        <button class="start-level-btn" @click="startLevel">开始挑战</button>
      </div>
      
      <div class="questions-list">
        <h2>题目列表</h2>
        <div class="question-item" v-for="(question, index) in questions" :key="question.question_id" 
             :class="{ answered: isQuestionAnswered(question.question_id), correct: isQuestionCorrect(question.question_id) }">
          <div class="question-header">
            <span class="question-number">题目 {{ index + 1 }}</span>
            <span class="question-status" v-if="isQuestionAnswered(question.question_id)">
              {{ isQuestionCorrect(question.question_id) ? '✅ 已答对' : '❌ 已答错' }}
            </span>
            <span class="question-status unanswered" v-else>❓ 未作答</span>
          </div>
          <p class="question-content">{{ question.content }}</p>
          <button class="view-question-btn" @click="viewQuestion(index)">查看题目</button>
        </div>
      </div>
      
      <div class="loading" v-if="loading">
        <p>正在加载关卡详情...</p>
      </div>
      
      <div class="error" v-if="error">
        <p>加载关卡详情失败: {{ error }}</p>
        <button class="retry-btn" @click="loadLevelDetail">重试</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getLevelDetail, getLevelProgress } from '../api/challenge'

// 使用路由
const route = useRoute()
const router = useRouter()

// 定义题目和选项类型
interface Option {
  option_id: number;
  content: string;
}

interface Question {
  question_id: number;
  content: string;
  options: Option[];
  is_answered?: boolean;
  is_correct?: boolean;
  user_selected_option_id?: number;
}

// 定义关卡详情类型
interface LevelDetail {
  level_id: number;
  level_name: string;
  total_questions: number;
  answered_questions: number;
  correct_answers: number;
  completion_rate: number;
  accuracy_rate: number;
  points?: number;
  time_limit?: number;
  stars?: number; // 星级数量，1-3
  [key: string]: any;
}

// 数据状态
const levelDetail = ref<LevelDetail>({} as LevelDetail)
const questions = ref<Question[]>([])
const loading = ref(true)
const error = ref('')
const userProgress = ref<{[key: number]: {is_answered: boolean, is_correct: boolean}}>({})

// 计算关卡星级
const calculateStars = (level: LevelDetail) => {
  if (!level.accuracy_rate || level.accuracy_rate === 0) return 0;
  
  const accuracy = level.accuracy_rate;
  if (accuracy >= 0.9) return 3; // 90%以上正确率得3星
  if (accuracy >= 0.7) return 2; // 70%-90%正确率得2星
  return 1; // 低于70%正确率得1星
};

// 获取关卡ID
const levelId = route.params.levelId ? parseInt(route.params.levelId as string) : 0

// 返回关卡列表
const goBackToList = () => {
  router.push('/level-list')
}

// 加载关卡详情
const loadLevelDetail = async () => {
  try {
    console.log('[LevelDetail] [DEBUG] 开始加载关卡详情:', levelId)
    loading.value = true
    error.value = ''
    
    // 同时获取关卡详情和用户进度
    const [detailResponse, progressResponse] = await Promise.all([
      getLevelDetail(levelId),
      getLevelProgress(levelId)
    ])
    
    console.log('[LevelDetail] [DEBUG] 关卡详情接口响应:', detailResponse)
    console.log('[LevelDetail] [DEBUG] 关卡进度接口响应:', progressResponse)
    
    // 处理关卡详情
    if (detailResponse && typeof detailResponse === 'object' && 'success' in detailResponse && detailResponse.success && 'data' in detailResponse && detailResponse.data) {
      const detailData = detailResponse.data.level || detailResponse.data;
      levelDetail.value = {
        level_id: detailData.level_id,
        level_name: detailData.level_name,
        total_questions: detailData.questions?.length || 0,
        answered_questions: 0,
        correct_answers: 0,
        completion_rate: 0,
        accuracy_rate: 0,
        points: detailData.points,
        time_limit: detailData.time_limit
      }
      
      // 设置题目数据
      questions.value = (detailData.questions || []).map((q: any) => ({
        question_id: q.question_id,
        content: q.content,
        options: (q.options || []).map((opt: any) => ({
          option_id: opt.option_id,
          content: opt.content
        }))
      }))
    } else {
      console.warn('[LevelDetail] [DEBUG] 关卡详情响应数据为空或格式不正确')
      const message = typeof detailResponse === 'object' && 'message' in detailResponse ? (detailResponse as any).message : '获取关卡详情失败'
      error.value = message || '获取关卡详情失败'
    }
    
    // 处理用户进度
    if (progressResponse && typeof progressResponse === 'object' && 'success' in progressResponse && progressResponse.success && 'data' in progressResponse && progressResponse.data) {
      // 构建用户答题状态映射
      const progressData = progressResponse.data.questions || []
      userProgress.value = {}
      progressData.forEach((q: any) => {
        userProgress.value[q.question_id] = {
          is_answered: q.is_answered || false,
          is_correct: q.is_correct || false
        }
      })
      
      // 更新关卡统计信息
      if (progressResponse.data.level_info) {
        levelDetail.value.answered_questions = progressResponse.data.level_info.answered_questions || 0
        levelDetail.value.correct_answers = progressResponse.data.level_info.correct_answers || 0
        levelDetail.value.completion_rate = progressResponse.data.level_info.completion_rate || 0
        levelDetail.value.accuracy_rate = progressResponse.data.level_info.accuracy_rate || 0
        
        // 如果关卡已完成，计算星级
        if (levelDetail.value.answered_questions === levelDetail.value.total_questions && levelDetail.value.total_questions > 0) {
          levelDetail.value.stars = calculateStars(levelDetail.value)
        }
      }
    }
  } catch (err: any) {
    console.error('[LevelDetail] [ERROR] 加载关卡详情失败:', err)
    error.value = err.message || '加载失败'
  } finally {
    loading.value = false
    console.log('[LevelDetail] [DEBUG] 关卡详情加载完成')
  }
}

// 检查题目是否已作答
const isQuestionAnswered = (questionId: number) => {
  return userProgress.value[questionId] ? userProgress.value[questionId].is_answered : false
}

// 检查题目是否答对
const isQuestionCorrect = (questionId: number) => {
  return userProgress.value[questionId] ? userProgress.value[questionId].is_correct : false
}

// 查看题目
const viewQuestion = (index: number) => {
  console.log('[LevelDetail] [DEBUG] 查看题目:', index)
  // 跳转到关卡答题页面，并传递题目索引
  router.push(`/level-quiz/${levelId}?questionIndex=${index}`)
}

// 开始挑战关卡（从第一题开始）
const startLevel = () => {
  console.log('[LevelDetail] [DEBUG] 开始挑战关卡:', levelId)
  // 跳转到关卡答题页面，从第一题开始
  router.push(`/level-quiz/${levelId}?questionIndex=0`)
}

// 组件挂载时加载数据
onMounted(() => {
  console.log('[LevelDetail] [DEBUG] 组件挂载完成，开始加载关卡详情')
  loadLevelDetail()
})

// 组件激活时重新加载数据（用于从答题结果页面返回时更新状态）
onActivated(() => {
  console.log('[LevelDetail] [DEBUG] 组件激活，重新加载关卡详情')
  loadLevelDetail()
})
</script>

<style scoped>
.level-detail {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 1.8rem;
  margin: 0;
  color: #2c3e50;
  flex: 1;
  text-align: center;
  padding: 0 20px;
}

.back-btn {
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  white-space: nowrap;
  background-color: #f8f9fa;
  color: #495057;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #e9ecef;
}

.spacer {
  width: 100px;
}

.level-content {
  max-width: 800px;
  margin: 0 auto;
}

.level-info-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 25px;
  box-sizing: border-box;
  margin-bottom: 30px;
}

.level-info-card h2 {
  color: #2c3e50;
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 1.5rem;
}

.level-info-card p {
  margin: 10px 0;
  padding: 8px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.level-info-card .star {
  font-size: 1.2rem;
}

.level-info-card .star.filled {
  color: #ffcc00;
}

.level-info-card .star.empty {
  color: #e0e0e0;
}

.start-level-btn {
  background-color: #42b983;
  color: white;
  padding: 12px 30px;
  border-radius: 25px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 20px;
}

.start-level-btn:hover {
  background-color: #359c6d;
  transform: scale(1.05);
}

.questions-list h2 {
  color: #2c3e50;
  margin-top: 30px;
  margin-bottom: 20px;
  font-size: 1.5rem;
}

.question-item {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 20px;
  box-sizing: border-box;
  margin-bottom: 20px;
  border-left: 5px solid #f8f9fa;
  transition: all 0.3s;
}

.question-item.answered {
  border-left-color: #42b983;
}

.question-item.correct {
  border-left-color: #42b983;
  background-color: #e8f5ee;
}

.question-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.question-number {
  font-weight: bold;
  color: #2c3e50;
}

.question-status {
  font-weight: bold;
  color: #42b983;
}

.question-status.unanswered {
  color: #6c757d;
}

.question-content {
  color: #495057;
  margin-bottom: 20px;
  line-height: 1.6;
}

.view-question-btn {
  background-color: #6c757d;
  color: white;
  padding: 8px 20px;
  border-radius: 20px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
}

.view-question-btn:hover {
  background-color: #5a6268;
  transform: scale(1.05);
}

.loading, .error {
  text-align: center;
  padding: 40px 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.loading p, .error p {
  margin: 0;
  color: #6c757d;
  font-size: 1.1rem;
}

.retry-btn {
  background-color: #ff6b35;
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 15px;
}

.retry-btn:hover {
  background-color: #e55a2b;
  transform: scale(1.05);
}

@media (max-width: 768px) {
  .level-detail {
    padding: 15px;
  }
  
  .page-header {
    padding: 15px;
  }
  
  .page-header h1 {
    font-size: 1.5rem;
  }
  
  .level-info-card {
    padding: 20px;
  }
  
  .question-item {
    padding: 15px;
  }
  
  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .level-detail {
    padding: 10px;
  }
  
  .header-top {
    flex-direction: column;
    gap: 15px;
  }
  
  .page-header h1 {
    font-size: 1.3rem;
    padding: 0;
  }
  
  .back-btn {
    padding: 8px 15px;
    font-size: 0.9rem;
  }
  
  .level-info-card {
    padding: 15px;
  }
  
  .level-info-card h2 {
    font-size: 1.3rem;
  }
}
</style>